<template>
  <div class="expert-appointment">
    <!-- 头部 -->
    <div class="header-section">
      <div class="header-title">
        <el-icon class="title-icon"><User /></el-icon>
        <h1>专家预约</h1>
      </div>
      <div class="header-subtitle">
        <p>选择专业领域专家，获取一对一专业指导</p>
      </div>
    </div>

    <!-- 专家列表 -->
    <div class="experts-section">
      <el-card class="experts-card">
        <template #header>
          <div class="experts-header">
            <span class="experts-title">专家团队</span>
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索专家姓名或专业领域"
                prefix-icon="Search"
                clearable
                style="width: 300px;"
                @input="handleSearch"
              />
            </div>
          </div>
        </template>

        <div class="experts-grid">
          <el-card
            v-for="expert in filteredExperts"
            :key="expert.id"
            class="expert-card"
            shadow="hover"
          >
            <template #header>
              <div class="expert-header">
                <div class="expert-avatar">
                  <el-avatar :size="80" :src="expert.avatar" />
                </div>
                <div class="expert-basic-info">
                  <h3 class="expert-name">{{ expert.name }}</h3>
                  <p class="expert-title">{{ expert.title }}</p>
                  <el-tag :type="getExpertTypeTag(expert.type)" size="small">
                    {{ expert.type }}
                  </el-tag>
                </div>
              </div>
            </template>

            <div class="expert-content">
              <div class="expert-specialty">
                <el-icon><Collection /></el-icon>
                <span class="label">专业领域：</span>
                <span class="value">{{ expert.specialty.join('、') }}</span>
              </div>
              
              <div class="expert-experience">
                <el-icon><Medal /></el-icon>
                <span class="label">从业经验：</span>
                <span class="value">{{ expert.experience }}年</span>
              </div>

              <div class="expert-rating">
                <el-rate
                  v-model="expert.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value} 分"
                />
              </div>

              <div class="expert-intro">
                <p>{{ expert.introduction }}</p>
              </div>

              <div class="expert-stats">
                <div class="stat-item">
                  <span class="stat-number">{{ expert.consultCount }}</span>
                  <span class="stat-label">咨询服务</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ expert.successRate }}%</span>
                  <span class="stat-label">解决率</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ expert.responseTime }}分钟</span>
                  <span class="stat-label">平均响应</span>
                </div>
              </div>
            </div>

            <template #footer>
              <div class="expert-footer">
                <el-button
                  type="primary"
                  @click="handleOnlineAppointment(expert)"
                  class="appointment-btn"
                >
                  <el-icon><VideoCamera /></el-icon>
                  线上答疑
                </el-button>
                <el-button
                  type="success"
                  @click="handleOfflineAppointment(expert)"
                  class="appointment-btn"
                >
                  <el-icon><Location /></el-icon>
                  线下预约
                </el-button>
              </div>
            </template>
          </el-card>
        </div>
      </el-card>
    </div>

    <!-- 预约对话框 -->
    <el-dialog
      v-model="showAppointmentDialog"
      :title="appointmentDialogTitle"
      width="600px"
      :close-on-click-modal="false"
      class="appointment-dialog"
    >
      <el-form
        ref="appointmentFormRef"
        :model="appointmentForm"
        :rules="appointmentRules"
        label-width="100px"
      >
        <el-form-item label="专家信息">
          <div class="expert-summary">
            <el-avatar :size="60" :src="selectedExpert?.avatar" />
            <div class="expert-details">
              <div class="expert-name">{{ selectedExpert?.name }}</div>
              <div class="expert-title">{{ selectedExpert?.title }}</div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="预约类型" prop="appointmentType">
          <el-radio-group v-model="appointmentForm.appointmentType" disabled>
            <el-radio :label="1">线上答疑</el-radio>
            <el-radio :label="2">线下预约</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="问题描述" prop="problemDescription">
          <el-input
            v-model="appointmentForm.problemDescription"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您遇到的问题，这将帮助专家更好地为您服务"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item v-if="appointmentForm.appointmentType === 1" label="预约时间" prop="appointmentTime">
          <el-date-picker
            v-model="appointmentForm.appointmentTime"
            type="datetime"
            placeholder="选择预约时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item v-else label="预约地点" prop="location">
          <el-input
            v-model="appointmentForm.location"
            placeholder="请输入期望的会面地点"
          />
        </el-form-item>

        <el-form-item label="联系方式" prop="contact">
          <el-input
            v-model="appointmentForm.contact"
            placeholder="请输入您的手机号码"
          />
        </el-form-item>

        <el-form-item label="补充说明">
          <el-input
            v-model="appointmentForm.remarks"
            type="textarea"
            :rows="2"
            placeholder="可补充说明您的其他需求"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAppointmentDialog = false" size="large">取消</el-button>
        <el-button
          type="primary"
          @click="submitAppointment"
          :loading="submittingAppointment"
          size="large"
        >
          提交预约
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User, Search, Collection, Medal, VideoCamera, Location
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const showAppointmentDialog = ref(false)
const submittingAppointment = ref(false)
const selectedExpert = ref(null)

const appointmentFormRef = ref(null)

// 专家数据
const experts = ref([
  {
    id: 1,
    name: '张教授',
    title: '农业种植专家',
    type: '种植专家',
    avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop',
    specialty: ['蔬菜种植', '果树栽培', '土壤改良'],
    experience: 15,
    rating: 4.8,
    introduction: '长期从事农业种植技术研究，在蔬菜和果树种植方面有丰富的实践经验。',
    consultCount: 256,
    successRate: 95,
    responseTime: 30
  },
  {
    id: 2,
    name: '李博士',
    title: '植物保护专家',
    type: '植保专家',
    avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop',
    specialty: ['病虫害防治', '农药使用', '生物防治'],
    experience: 12,
    rating: 4.9,
    introduction: '专注于植物病虫害防治研究，擅长制定科学的病虫害综合防治方案。',
    consultCount: 189,
    successRate: 98,
    responseTime: 25
  },
  {
    id: 3,
    name: '王工程师',
    title: '农业机械专家',
    type: '机械专家',
    avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=100&h=100&fit=crop',
    specialty: ['农机操作', '设备维护', '机械化种植'],
    experience: 10,
    rating: 4.7,
    introduction: '熟悉各类农业机械的操作与维护，致力于推广农业机械化技术。',
    consultCount: 142,
    successRate: 92,
    responseTime: 35
  },
  {
    id: 4,
    name: '赵教授',
    title: ' crop expert',
    type: ' crop expert',
    avatar: 'https://images.unsplash.com/photo-1517849845534-46d48c363129?w=100&h=100&fit=crop',
    specialty: [' crop expert', ' crop expert', ' crop expert'],
    experience: 8,
    rating: 4.6,
  },
  {
    id: 5,
    name: '钱老师',
    title: ' crop expert',
    type: ' crop expert',
    avatar: 'https://images.unsplash.com/photo-1513956589380-bad6acb9b9d4?w=100&h=100&fit=crop',
    specialty: [' crop expert', ' crop expert', ' crop expert'],
    experience: 6,
  },
  {
    id: 6,
    name: '孙老师',
    title: ' crop expert',
    type: ' crop expert',
    avatar: 'https://images.unsplash.com/photo-1513956589380-bad6acb9b9d4?w=100&h=100&fit=crop',
    specialty: [' crop expert', ' crop expert', ' crop expert'],
    experience: 4,
  }
])

// 预约表单数据
const appointmentForm = reactive({
  appointmentType: 1,
  problemDescription: '',
  appointmentTime: '',
  location: '',
  contact: '',
  remarks: ''
})

// 表单验证规则
const appointmentRules = {
  problemDescription: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 10, max: 500, message: '问题描述长度为10-500个字符', trigger: 'blur' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入预约地点', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 计算属性
const filteredExperts = computed(() => {
  if (!searchKeyword.value) return experts.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return experts.value.filter(expert => 
    expert.name.toLowerCase().includes(keyword) ||
    expert.title.toLowerCase().includes(keyword) ||
    expert.specialty.some(s => s.toLowerCase().includes(keyword))
  )
})

const appointmentDialogTitle = computed(() => {
  const typeText = appointmentForm.appointmentType === 1 ? '线上答疑' : '线下预约'
  return `预约${selectedExpert.value?.name}专家 - ${typeText}`
})

// 方法
const getExpertTypeTag = (type) => {
  const types = {
    '种植专家': 'success',
    '植保专家': 'warning',
    '机械专家': 'primary',
    '养殖专家': 'info'
  }
  return types[type] || 'info'
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleOnlineAppointment = (expert) => {
  selectedExpert.value = expert
  appointmentForm.appointmentType = 1
  showAppointmentDialog.value = true
}

const handleOfflineAppointment = (expert) => {
  selectedExpert.value = expert
  appointmentForm.appointmentType = 2
  showAppointmentDialog.value = true
}

const submitAppointment = async () => {
  if (!appointmentFormRef.value) return
  
  try {
    await appointmentFormRef.value.validate()
    
    submittingAppointment.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 保存预约记录
    const appointmentRecord = {
      id: Date.now(),
      expertId: selectedExpert.value.id,
      expertName: selectedExpert.value.name,
      expertAvatar: selectedExpert.value.avatar,
      appointmentType: appointmentForm.appointmentType,
      problemDescription: appointmentForm.problemDescription,
      appointmentTime: appointmentForm.appointmentTime,
      location: appointmentForm.location,
      contact: appointmentForm.contact,
      remarks: appointmentForm.remarks,
      applyTime: new Date().toISOString(),
      status: 0 // 0-待确认, 1-已确认, 2-已完成, 3-已取消
    }
    
    // 保存到本地存储
    const storedAppointments = JSON.parse(localStorage.getItem('expertAppointments') || '[]')
    storedAppointments.unshift(appointmentRecord)
    localStorage.setItem('expertAppointments', JSON.stringify(storedAppointments))
    
    ElMessage.success('预约申请提交成功，请等待专家确认')
    showAppointmentDialog.value = false
    resetAppointmentForm()
    
    // 跳转到预约记录页面
    router.push('/farmer/expertAssistance/appointmentRecord')
  } catch (error) {
    console.error('提交预约失败:', error)
  } finally {
    submittingAppointment.value = false
  }
}

const resetAppointmentForm = () => {
  Object.assign(appointmentForm, {
    appointmentType: 1,
    problemDescription: '',
    appointmentTime: '',
    location: '',
    contact: '',
    remarks: ''
  })
  selectedExpert.value = null
  if (appointmentFormRef.value) {
    appointmentFormRef.value.clearValidate()
  }
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.expert-appointment {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 */
.header-section {
  text-align: center;
  margin-bottom: 24px;
  padding: 40px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-bottom: 12px;
}

.title-icon {
  font-size: 40px;
}

.header-title h1 {
  margin: 0;
  font-size: 36px;
  font-weight: 700;
}

.header-subtitle p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

/* 专家区域 */
.experts-section {
  margin-bottom: 24px;
}

.experts-card {
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.experts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.experts-title {
  font-size: 20px;
  font-weight: 600;
  color: #2d3748;
}

/* 专家网格 */
.experts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 24px;
  margin-top: 16px;
}

.expert-card {
  border-radius: 12px;
  transition: all 0.3s ease;
}

.expert-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.expert-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.expert-basic-info {
  flex: 1;
}

.expert-name {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #2d3748;
}

.expert-title {
  margin: 0 0 8px 0;
  color: #718096;
  font-size: 14px;
}

/* 专家内容 */
.expert-content {
  padding: 16px 0;
}

.expert-specialty,
.expert-experience {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
}

.expert-specialty .el-icon,
.expert-experience .el-icon {
  color: #667eea;
}

.label {
  color: #718096;
  font-weight: 500;
}

.value {
  color: #2d3748;
  font-weight: 600;
}

.expert-rating {
  margin-bottom: 16px;
}

.expert-intro {
  margin-bottom: 16px;
}

.expert-intro p {
  margin: 0;
  color: #718096;
  font-size: 14px;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.expert-stats {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #667eea;
}

.stat-label {
  font-size: 12px;
  color: #718096;
}

.expert-footer {
  display: flex;
  gap: 12px;
}

.appointment-btn {
  flex: 1;
  border-radius: 8px;
  font-weight: 600;
}

/* 预约对话框 */
.appointment-dialog {
  border-radius: 16px;
}

.expert-summary {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.expert-details {
  display: flex;
  flex-direction: column;
}

.expert-details .expert-name {
  font-size: 18px;
  margin-bottom: 4px;
}

.expert-details .expert-title {
  color: #718096;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .expert-appointment {
    padding: 16px;
  }
  
  .header-title {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-title h1 {
    font-size: 28px;
  }
  
  .experts-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .search-box {
    width: 100%;
  }
  
  .search-box .el-input {
    width: 100% !important;
  }
  
  .experts-grid {
    grid-template-columns: 1fr;
  }
  
  .expert-footer {
    flex-direction: column;
  }
  
  .expert-stats {
    flex-direction: column;
    gap: 12px;
  }
}
</style>